package com.example.bletestutils.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;


import com.example.bletestutils.R;

import java.util.Timer;
import java.util.TimerTask;

public class KnobView extends View {
    private float initialAngle = 0;
    private float totalRotation = 0;

    // 控件宽
    private int width;
    // 控件高
    private int height;

    // 按钮图片
    private Bitmap buttonImage = BitmapFactory.decodeResource(getResources(),
            R.mipmap.vol);

    // 按钮图片阴影
    private Bitmap buttonImageShadow = BitmapFactory.decodeResource(getResources(),
            R.mipmap.btn_rotate_shadow);

    // 旋转按钮画笔
    private Paint buttonPaint = new Paint();


    public KnobView(Context context) {
        this(context, null);
    }

    public KnobView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public KnobView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }


    /**
     * 绘制旋转按钮
     *
     * @param canvas 画布
     */
    private void drawButton(Canvas canvas) {
        // 按钮宽高
        int buttonWidth = buttonImage.getWidth();
        int buttonHeight = buttonImage.getHeight();
        // 按钮阴影宽高
        int buttonShadowWidth = buttonImageShadow.getWidth();
        int buttonShadowHeight = buttonImageShadow.getHeight();

        // 绘制按钮阴影
        canvas.drawBitmap(buttonImageShadow, (width - buttonShadowWidth) / 2,
                (height - buttonShadowHeight) / 2, buttonPaint);

        Matrix matrix = new Matrix();
        // 设置按钮位置，移动到控件中心
        matrix.setTranslate((width - buttonWidth) / 2, (height - buttonHeight) / 2);
        // 设置旋转角度，旋转中心为控件中心，当前也是按钮中心
        matrix.postRotate(totalRotation + 90, width / 2, height / 2);
//        Log.e("totalRotation", "" + totalRotation);

        //设置抗锯齿
//        canvas.setDrawFilter(paintFlagsDrawFilter);
//        canvas.drawBitmap(buttonImage, matrix, buttonPaint);
        canvas.drawBitmap(buttonImage, matrix, buttonPaint);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        // 控件宽、高
        width = height = Math.min(h, w);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        float x = event.getX();
        float y = event.getY();

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                initialAngle = calculateAngle(x, y);
                if (!isRunning) {
                    isRunning = true;
                    startTimer();
                }
                break;
            case MotionEvent.ACTION_MOVE:
                float currentAngle = calculateAngle(x, y);
                float angleDiff = currentAngle - initialAngle;
                if (angleDiff > 180) {
                    angleDiff -= 360;
                } else if (angleDiff < -180) {
                    angleDiff += 360;
                }
                totalRotation += angleDiff;
                initialAngle = currentAngle;
                invalidate();
                break;
            case MotionEvent.ACTION_UP:
                isRunning = false;
                timer.cancel();
                timer = null;

                //取消后，最后一次不满100毫秒的再发生一次变化的数据
                float v = totalRotation - tempTotalRotation;
                if (listener != null) {
                    listener.onChangedValue(v);
                }
                tempTotalRotation = totalRotation;
                //取消后，最后一次不满100毫秒的再发生一次变化的数据

                if (listener != null) {
                    listener.onFinalValue(totalRotation);
                }
//                Toast.makeText(getContext(), "" + totalRotation, Toast.LENGTH_SHORT).show();
//                totalRotation = 0;
//                invalidate();
                break;
        }
// 请求父视图不要拦截触摸事件
        getParent().requestDisallowInterceptTouchEvent(true);
        // 处理触摸事件
//        return super.onTouchEvent(event);
        return true;
    }

    private float calculateAngle(float x, float y) {
        float centerX = getWidth() / 2f;
        float centerY = getHeight() / 2f;
        return (float) Math.toDegrees(Math.atan2(y - centerY, x - centerX));
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        float centerX = getWidth() / 2f;
        float centerY = getHeight() / 2f;

        drawButton(canvas);

        canvas.rotate(totalRotation, centerX, centerY);


    }

    private boolean isRunning = false;

    private Timer timer;

    private float tempTotalRotation = 0;

    private synchronized void startTimer() {
        tempTotalRotation = totalRotation;
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                float v = totalRotation - tempTotalRotation;
                if (listener != null) {
                    listener.onChangedValue(v);
                }
                tempTotalRotation = totalRotation;
            }
        }, 200, 200);
    }

    public interface OnResultListener {
        void onChangedValue(float value);

        void onFinalValue(float finalValue);
    }

    private OnResultListener listener;

    public void setListener(OnResultListener listener) {
        this.listener = listener;
    }

}